import socket as soc
import Tools.XMLTool as xml


class Socket_Server:
    def __init__(self):
        doc = xml.XMLTools()
        self.host = soc.gethostbyname(soc.gethostname())    # bind地址自动获取本机
        self.port = int(doc.Read_xml('../Config.xml', 'Socket_Server_Config/Port_Address')) if \
            doc.Xml_Exist('../Config.xml') else 51423
        self.s = soc.socket(soc.AF_INET, soc.SOCK_STREAM)
        self.s.setsockopt(soc.SOL_SOCKET, soc.SO_REUSEADDR, 1)     # 让socket 端口可立即复用

    def start(self):
        self.s.bind((self.host,self.port))
        print('服务端{}启动，等待连接。。。'.format(self.s.getsockname()))
        self.s.listen(5)   # 此处其实是个参数设置

    def wait_connect(self):
        self.ClientSocket, ClientAddress = self.s.accept()
        print('客户端{}连接成功'.format(ClientAddress))
        self.ClientSocket.send('Server Connected'.encode())

    def listen(self):
        print('开始监听')
        while(True):
            try:
                message=self.ClientSocket.recv(1024)
                if (message is not '' and message is not None):
                    print('客户端消息：')
                    print(message.decode())
                else:
                    continue
            except soc.error as e:
                print("连接错误："+str(e))
                self.wait_connect()
                self.listen()
                break

    def send_message(self,message):
        try:
            self.ClientSocket.send(message.encode())   # 此处发送消息
            return True
        except IOError as e:
            print(str(e))
            return False


    def Send_Receive(self,message):
        """
        常用来发送指令，返回初始观测值
        :param message:
        :return rc: 返回完整结构的字符串
        """
        self.ClientSocket.send(message.encode())
        rec = self.ClientSocket.recv(1024)
        while rec is None:
            rec = self.ClientSocket.recv(1024).decode()
        return rec

    def wait_answer(self):
        """
        等待客户端准备好发送数据
        :return:
        """
        answer=True
        print('等待客户端数据准备中。。。')
        while answer:
            message = self.ClientSocket.recv(1024)
            if message is not None:
                answer=False
        return message.decode()

    def relay(self):
        pass







